
function [p q] = SemiImplicit_Trapezoidal(dt)
global U  h  g  p  q  nt dx h1 x p_global tmax L steps itermax ;

dx1=1/dx;
dx2 = 1/(dx*dx);
dt2= 1/dt;


%---- Construct the spatial Discretization Matrix------%
A = zeros(x,x);
A(1,x) = -U*0.5*dx1;
A(1,2) =  U*0.5*dx1;
for k=2:x-1
    A(k,k-1) = -U*0.5*dx1;
    A(k,k+1) =  U*0.5*dx1;
end

A(x,x-1) = -U*0.5*(1/dx);
A(x,1)   =  U*0.5*(1/dx);



B=zeros(x,x);

B(1,x)=h*dx2;
B(1,2)=h*dx2;
B(1,1)=-2*h*dx2;
for k=2:x-1
    B(k,k)= -2*h*dx2; 
    B(k,k-1)=h*dx2;
    B(k,k+1)=h*dx2;
end
B(x,1)=h*dx2;
B(x,x-1)=h*dx2;
B(x,x)=-2*h*dx2;


b=-h*h/3*dx2;

C=zeros(x,x);
C(1,x)= b;
C(1,2)= b;
C(1,1)= -2*b;

for k=2:x-1
    C(k,k-1)=b;
    C(k,k+1) =b;
    C (k,k) = -2*b;
end

C(x,x-1)= b;
C(x,1)= b;
C(x,x)= -2*b;


b=h*h/3*dx2;

D=zeros(x,x);
D(1,x)= b;
D(1,2)= b;
D(1,1)= -2*b;

for k=2:x-1
    D(k,k-1)=b;
    D(k,k+1) =b;
    D (k,k) = -2*b;
end

D(x,x-1)= b;
D(x,1)= b;
D(x,x)= -2*b;

n = -2/15*h*h*h*dx2;
E=zeros(x,x);
E(1,x)= n;
E(1,2)= n ;
E(1,1)= -2*n+h/3;

for k=2:x-1
    E(k,k-1)=n;
    E(k,k+1) =n;
    E (k,k) = -2*n+h/3;
end

E(x,x-1)= n;
E(x,1)= n;
E(x,x)= -2*n+h/3;


I = eye(x,x);  

r= -E\(D*q);


p_n=p;
q_n=q;

for n=2:nt+1;      
       
           % advance q explicitly by Forward Euler method
            if (n==2)
                pex = p_n - dt*(A*p_n - C*r);
                rhs = (dt2*I-A)*q_n - g*0.5*(p_n+pex);
                q_np1 = (dt2*I - 0.5*dt*g*B)\rhs;
                r= -E\(D*q_np1);
                p_np1 = pex - dt*B*q_np1;
            else
                pex = p_nm1 - 2*dt*(A*p_n - C*r);
                rhs = (dt2*I-A)*q_n - g*0.5*(p_n+pex);
                q_np1 = (dt2*I - dt*g*B)\rhs;
                r= -E\(D*q_np1);
                p_np1 = pex - 2*dt*B*q_np1;
            end
                       
            p_nm1 = p_n;
            p_n = p_np1;
            q_n = q_np1;
            p=p_n;        
          
            
           
    if rem(n,100)==0

        refreshdata(h1,'caller') % Evaluate p in the function workspace
        drawnow
    end

end
display('Completed Successfully');